package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author benben278
 * @create 2022-03-15 10:14
 */
@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {
    @Autowired
    private OrderSettingService orderSettingService;
    //文件上传，实现预约设置数据批量导入
    @RequestMapping("/upload.do")
    public Result upload(@RequestParam("excelFile")MultipartFile excelFile){
        try {
            List<String[]> list= POIUtils.readExcel(excelFile);//使用POI解析表格数据
            List<OrderSetting> data=new ArrayList<>();//将数据封装成实体类
            for (String[] strings : list) {
                String orderDate = strings[0];
                String number = strings[1];
                OrderSetting orderSetting = new OrderSetting(new Date(orderDate), Integer.parseInt(number));//将字符串转成日期格式和数字格式，再封装从实体类属性
                data.add(orderSetting);
            }
            //通过dubbo远程调用服务实现数据批量导入到数据库
            orderSettingService.add(data);
            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        }catch (IOException e){
            e.printStackTrace();
            //文件解析失败
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
    }
    //根据年月查询对应的预约设置数据
    @RequestMapping("/getOrderSettingByMonth.do")
    public Result getOrderSettingByMonth(String date){//date格式为：yyyy-mm
       try{
           List<Map> list=orderSettingService.getOrderSettingByMonth(date);//基于页面数据格式的要求，返回数据封装成Map格式是比较合理和灵活的。
           return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS,list);
       }catch (Exception e){
           e.printStackTrace();
          return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
       }
    }
    //选择日期设置预约数据
    @RequestMapping("/editNumberByDate.do")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting){
        try{
            orderSettingService.editNumberByDate(orderSetting);//基于页面数据格式的要求，返回数据封装成Map格式是比较合理和灵活的。
            return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.ORDERSETTING_FAIL);
        }
    }
}
